

const fs = require('fs');
const path = require('path');
const { dbUrl } = require("./utils/url");
const { MongoClient, ObjectId } = require('mongodb');
// ================= 配置参数 =================
const uri = dbUrl; // 替换为你的 MongoDB 连接字符串
const dbName = "jinbeibei";
const importDir = path.join(__dirname, 'backup_output');
const dropCollectionBeforeImport = true;

// 判断是否为 ObjectId 扩展格式并转换
function deserialize(doc) {
    for (let key in doc) {
        if (doc[key] && doc[key]["$oid"]) {
            try {
                doc[key] = new ObjectId(doc[key]["$oid"]);
            } catch (e) {}
        }
    }
    return doc;
}

async function importDatabase() {
    const client = new MongoClient(uri, {
        // useNewUrlParser: true,
        // useUnifiedTopology: true,
    });

    try {
        await client.connect();
        console.log("✅ 成功连接到 MongoDB");

        const db = client.db(dbName);

        const files = fs.readdirSync(importDir).filter(file => file.endsWith('.json'));

        if (files.length === 0) {
            console.log("❌ 没有找到可导入的 .json 文件");
            return;
        }

        for (const file of files) {
            const collectionName = path.basename(file, '.json');
            const filePath = path.join(importDir, file);

            console.log(`导入集合: ${collectionName} 来自文件: ${filePath}`);

            const collection = db.collection(collectionName);

            if (dropCollectionBeforeImport) {
                await collection.drop().catch(() => {});
                console.log(`🧹 已清空集合 ${collectionName}`);
            }

            const data = fs.readFileSync(filePath, 'utf-8');
            let docs = JSON.parse(data);

            if (!Array.isArray(docs)) {
                console.warn(`⚠️ 文件 ${file} 不是有效的 JSON 数组，跳过导入`);
                continue;
            }

            const deserializedDocs = docs.map(deserialize);

            if (deserializedDocs.length > 0) {
                await collection.insertMany(deserializedDocs);
                console.log(`✅ 成功导入 ${deserializedDocs.length} 条记录到集合 ${collectionName}`);
            } else {
                console.log(`ℹ️ 集合 ${collectionName} 为空，跳过导入`);
            }
        }

        console.log("🎉 数据库导入完成！");
    } catch (err) {
        console.error("❌ 导入失败:", err.message);
    } finally {
        await client.close();
    }
}

importDatabase();
